package com.elycio.fsz;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.elycio.fsz.tools.CommandType;
import com.elycio.fsz.views.ColorPickerView;

import java.util.Arrays;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback;
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class MainActivity extends AppCompatActivity {
    //获取activity_main.xml中的控件变量
    @SuppressLint("UseSwitchCompatOrMaterialCode")
    //开关按钮
    public Switch powerButton;
    //物体图片
    public ImageView imageView;
    //默认模式
    public Button defalutButton;
    //自定义模式
    public Button customButton;
    //呼吸灯
    public Button breathingButton;
    //亮度调节
    public SeekBar seekBar;

    public TextView brightnessTextView;

    public ColorPickerView myColorPickerView;

    public int brightness=0;

    //灯状态
    public boolean lightOn=false;

    //灯光模式
    public int lightMode=0;
    //数据包
    private final String TAG = "MainActivity";
    //当前是否连接
    boolean currentIsConnected = false;

    //private final String BLUETOOTH_MAC = "54:32:04:74:19:FA";
    private final Ble<BleDevice> ble = Ble.getInstance();
    private BleDevice shadowBoxDevice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        //String serviceUUID = "00000001-0000-1000-8000-00805f9b34fb";
        //String characteristicUUID = "00000002-0000-1000-8000-00805f9b34fb";
        ble.startScan(scanCallback);
        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        bindClickListener();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        //解绑监听
        super.onDestroy();
        ble.released();
    }

    //初始化
    @SuppressLint("ResourceAsColor")
    public void initView(){
        //开关按钮
         powerButton=findViewById(R.id.power_switch);
        //物体图片
         imageView=findViewById(R.id.imageView);
         imageView.setImageResource(R.drawable.showlight_off);
        //默认模式
         defalutButton=findViewById(R.id.button3);
        //自定义模式
         customButton=findViewById(R.id.button4);
        //呼吸灯
        breathingButton=findViewById(R.id.button5);
        //亮度调节
         seekBar=findViewById(R.id.seekBar);

        brightnessTextView=findViewById(R.id.brightness_text);

        myColorPickerView = findViewById(R.id.color_picker_view);

        //seekBar的最大值
        seekBar.setMax(255);
        //设置默认亮度值
        myColorPickerView.setColor(0xFFFFFFFF);


    }

    public void bindClickListener(){
        //seekBar的监听事件

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //亮度值显示 进度变化时
                runOnUiThread(() -> {
                    String percent= (int)(seekBar.getProgress() / 255.0f * 100) +"%";
                    brightnessTextView.setText(percent);
                    Log.d(TAG+":brightnessTextView", "brightnessTextView: " + percent);
                });
                brightness=progress;
                byte[] brightnessData = new byte[]{(byte) (progress & 0xff)};
                Log.d("brightnessData", "brightnessData: " + progress);
                sendLedData((byte) CommandType.SET_BRIGHTNESS.getValue(),brightnessData);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //开关按钮的监听事件
        powerButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                //开灯
                imageView.setImageResource(R.drawable.light_on);
                lightOn=true;
                sendLedData((byte)0x00,new byte[0]);
                //Toast.makeText(MainActivity.this, "打开灯", Toast.LENGTH_SHORT).show();
                breathingButton.setEnabled(true);
                customButton.setEnabled(true);
                defalutButton.setEnabled(true);
                myColorPickerView.setEnabled(true);
                seekBar.setEnabled(true);
                brightnessTextView.setEnabled(true);
            } else {
                //关灯
                imageView.setImageResource(R.drawable.showlight_off);
                lightOn=false;
                //发送关灯数据包
                sendLedData((byte)0xff,new byte[0]);
                //Toast.makeText(MainActivity.this, "关闭灯", Toast.LENGTH_SHORT).show();
                breathingButton.setEnabled(false);
                customButton.setEnabled(false);
                defalutButton.setEnabled(false);
                myColorPickerView.setEnabled(false);
                seekBar.setEnabled(false);
                brightnessTextView.setEnabled(false);
            }
        });


        //默认模式按钮的监听事件
        defalutButton.setOnClickListener(v -> {
            //设置灯光模式为默认模式
            lightMode=2;
            //设置按钮样式
            defalutButton.setBackgroundResource(R.drawable.button_black);
            customButton.setBackgroundResource(R.drawable.button_rect_white);
            breathingButton.setBackgroundResource(R.drawable.button_rect_white);
            //设置按钮字体颜色
            defalutButton.setTextColor(Color.WHITE);
            customButton.setTextColor(0xFF464646);
            breathingButton.setTextColor(0xFF464646);
            myColorPickerView.setVisibility(View.INVISIBLE);
            sendLedData((byte) lightMode, new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff});
        });
        //自定义模式按钮的监听事件
        customButton.setOnClickListener(v -> {
            //设置灯光模式为自定义模式
            lightMode=3;
            //设置按钮样式
            defalutButton.setBackgroundResource(R.drawable.button_rect_white);
            customButton.setBackgroundResource(R.drawable.button_black);
            breathingButton.setBackgroundResource(R.drawable.button_rect_white);
            //设置按钮字体颜色
            defalutButton.setTextColor(0xFF464646);
            customButton.setTextColor(Color.WHITE);
            breathingButton.setTextColor(0xFF464646);
            myColorPickerView.setVisibility(View.VISIBLE);
            int concurrentColor = myColorPickerView.getColor();
            int red = (concurrentColor & 0xff0000) >> 16;
            int green = (concurrentColor & 0x00ff00) >> 8;
            int blue = (concurrentColor & 0x0000ff);
            sendLedData((byte) lightMode, new byte[]{(byte) red, (byte) green, (byte) blue});
        });
        //呼吸灯按钮的监听事件
        breathingButton.setOnClickListener(v -> {
            //设置灯光模式为呼吸灯模式
            lightMode = 4;
            //设置按钮样式
            defalutButton.setBackgroundResource(R.drawable.button_rect_white);
            customButton.setBackgroundResource(R.drawable.button_rect_white);
            breathingButton.setBackgroundResource(R.drawable.button_black);
            //设置按钮字体颜色
            defalutButton.setTextColor(0xFF464646);
            customButton.setTextColor(0xFF464646);
            breathingButton.setTextColor(Color.WHITE);
            myColorPickerView.setVisibility(View.VISIBLE);
            int concurrentColor = myColorPickerView.getColor();
            int red = (concurrentColor & 0xff0000) >> 16;
            int green = (concurrentColor & 0x00ff00) >> 8;
            int blue = (concurrentColor & 0x0000ff);
            sendLedData((byte) lightMode, new byte[]{(byte) red, (byte) green, (byte) blue});
        });

        myColorPickerView.setOnColorPickerChangerListener((color,r,g,b)->{
            if(lightOn){
                sendLedData((byte) lightMode, new byte[]{(byte) r, (byte) g, (byte) b});
            }
        });

    }

    public void sendLedData(byte mode, byte[] data_to_send) {
        if(shadowBoxDevice==null){
            Toast.makeText(MainActivity.this, "影灯未连接" , Toast.LENGTH_SHORT).show();
            return;
        }
        byte[] data;
        if(mode==(byte)0xff){
            data= new byte[]{mode};
        } else if(mode==(byte)0x00){
            data= new byte[]{mode};
        }else if(mode==(byte)0x05){
            data= new byte[]{mode,data_to_send[0]};
        } else {
            data= new byte[]{mode, data_to_send[0], data_to_send[1], data_to_send[2]};
        }

        Log.d(TAG, "sendLedData(): " + Arrays.toString(data));
        ble.write(shadowBoxDevice,data,new BleWriteCallback<BleDevice>(){
            @Override
            public void onWriteSuccess(BleDevice o, BluetoothGattCharacteristic bluetoothGattCharacteristic) {}
            public void onWriteFailed(BleDevice device, int failedCode) {
                Toast.makeText(MainActivity.this, "数据发送失败！" , Toast.LENGTH_SHORT).show();
            }
        });
    }
    BleScanCallback<BleDevice> scanCallback = new BleScanCallback<BleDevice>() {
        @Override
        public void onLeScan(final BleDevice device, int rssi, byte[] scanRecord) {
            //Scanned devices
            if (device!=null && ("影灯").equals(device.getBleName())) {
                Log.d(TAG, "onLeScan: " + device.getBleName());
                ble.stopScan();
                ble.connect(device, new BleConnectCallback<BleDevice>(){
                    @Override
                    public void onConnectionChanged(BleDevice bleDevice){
                        if(("影灯").equals(device.getBleName())&&bleDevice.isConnected()){
                            currentIsConnected = true;
                            if(shadowBoxDevice!=null) shadowBoxDevice = device;
                        }else{
                            currentIsConnected = false;
                            shadowBoxDevice=null;
                            Toast.makeText(MainActivity.this, "影灯已断开" , Toast.LENGTH_SHORT).show();
                        }

                    }
                    @Override
                    public void onReady(BleDevice bleDevice){
                        currentIsConnected = true;
                        shadowBoxDevice = device;
                        Toast.makeText(MainActivity.this, "成功连接影灯" , Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onServicesDiscovered(BleDevice device, BluetoothGatt gatt) {

                    }
                    @Override
                    public void onConnectFailed(BleDevice device, int errorCode) {
                        Toast.makeText(MainActivity.this, "连接失败" , Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onStart() {
            super.onStart();
        }

        @Override
        public void onStop() {
            super.onStop();
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "onScanFailed: "+errorCode);
        }
    };

}